@echo off

if "%1"=="" (
	echo You have missed some parameters.
	echo Please, pass at least one parameter - function name.
	echo Press any key...
	pause> nul
) else (
	call :%1 %2 %3
)
goto :EOF



:configure
rem  Path to directory with sym-files
set SymDir=syms
rem  Output directory
set OutDir=libs
rem  Path to Loader API file
set ldrAPI=ldrAPI.def
rem  Path to header with constants
set Consts=..\SDK\consts.h

rem  Time and date detection
for /f "tokens=1-3 delims=/-:., " %%i in ('date /T') do set _date=%%k%%j%%i
for /f "tokens=1-2 delims=/-:., " %%i in ('time /T') do set _time=%%i%%j
set ver=%_date:~2,6%%_time:~0,1%
set now=%_date:~2,6%_%_time%

rem  Compiler, linker and other utilities options
set 7z=7z.exe
set pl=postlink.exe

exit /b %errorlevel%


:list
cls

setlocal enabledelayedexpansion

echo Please select your firmware:
echo  0) Build all libraries

set cnt=0
for %%a in (%SymDir%\*.sym) do (
	set /a cnt+=1
	echo  !cnt!^) %%~na
)

set /p sel=Your choice^> 
set fw=
set cnt=0

for %%a in (%SymDir%\*.sym) do (
	set /a cnt+=1
	if "%sel%"=="!cnt!" set fw=%%~na
)

if "%fw%"=="" (
	if not "%sel%"=="0" (
		set sel=1
	)
) else (
	set sel=0
)

endlocal& set errorlevel=%sel%& set firmware=%fw%

exit /b %errorlevel%


:build
if exist "%SymDir%\%~1.sym" (
	%pl% -stdlib "%SymDir%\%~1.sym" -def "%ldrAPI%" -header "%Consts%" -fw %~1 -v %~2
	
	if not errorlevel 1 (
		del /f /q "%OutDir%\%~1.bin"
		copy /y "std.lib" "%OutDir%\%~1.bin"
		ren "std.lib" "library.bin"
	)
)

exit /b %errorlevel%


:archive
call :configure

7z a -tzip -mx9 -xr!*svn* "%OutDir%\archive\libs_%now%.zip" ".\%OutDir%\*.bin"

exit /b %errorlevel%


:clean
goto clean_%~1
goto clean_exit

:clean_bin
del /f /q "*.bin"
goto clean_exit

:clean_all
del /f /q "%OutDir%\*.bin"

:clean_
del /f /q "*.bin" "*.sa"

:clean_exit
exit /b %errorlevel%